<template>
	<view style="padding: 30rpx;height: 100%;overflow: auto;">
		<u-search placeholder="输入内容" v-model="keyword" bgColor="#fff" :showAction="false" @search="search"></u-search>
		<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" style="margin-top: 30rpx;">
			<swiper-item>
				<view class="swiper-item" v-for="(item,index) in list" :key="index">
					<image :src="getUrl(item.image)" mode=""></image>
				</view>
			</swiper-item>
		</swiper>
		<view
			style="display: flex;flex-direction: column;padding: 0;margin-top: 30rpx;background-color: white;border-radius: 30rpx;">
			<u-tabs :list="list3" :current="current" lineColor="#96ea6f" @click="click"></u-tabs>
			<scroll-view scroll-x="true" style="width: 100%;">
				<view class="tabs" style="align-items: center;padding: 0 20rpx;">
					<view class=""
						style="width: 80rpx;height: 80rpx;display: flex;justify-content: center;align-items: center;border: 2rpx solid rgb(8, 187, 7);border-radius: 100px;margin-bottom: 30rpx;"
						@click="navCate">
						<u-icon name="edit-pen" size="24" color="rgb(8, 187, 7)"></u-icon>
					</view>
					<view class="tab" v-for="(item,index) in list1" :key="index" @click="toList(item)"
						v-if="chooseList.includes(item.id)">
						<image :src="getUrl(item.image)" mode=""
							style="width: 80rpx;height: 80rpx;border-radius: 10rpx;"></image>
						<view class="">
							{{item.name}}
						</view>
					</view>
				</view>
			</scroll-view>

		</view>

		<view class="items">
			<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" v-if="list2.length==0">
			</u-empty>

			<view class="item" v-for="(item,index) in list2" :key="index" @click="toDetail(item)" v-if="item.status==1">
				<view class="top">
					<u-avatar :src="item.userInfo.avatar"></u-avatar>
					<view class="" style="flex: 1;margin-left: 20rpx;">
						<view class="" v-if="item.userInfo">
							{{item.userInfo.username || '--'}}
						</view>
						<view class="" style="color: #7B7878;font-size: 24rpx;">
							{{formatTimestamp(item.createtime)}}
						</view>
					</view>
					<view class=""
						style="color: #2DBC26;font-size: 24rpx;margin-left: 10rpx;font-weight: 400;text-align: right;">
						{{parseFloat((Number(item.distance) / 1000).toFixed(2))}} km
					</view>
				</view>
				<view class="" style="margin: 10rpx 0;">
					{{item.title}}
				</view>
				<view class="imgs">
					<image :src="img" mode="" v-for="(img,ind) in item.images" :key="ind"></image>
				</view>
				<view class=""
					style="display: flex;align-items: center;justify-content: space-between;margin-top: 20rpx;color: #656565;">
					<view class="" style="display: flex;align-items: center;">
						<u-icon name="eye" color="#656565" size="22"></u-icon>
						<text style="margin-left: 6rpx;">浏览 {{item.view+1}}</text>
					</view>
					<view class="">
						收藏 {{item.collect}}
					</view>
				</view>
			</view>
		</view>
		<view class="" style="opacity: 0;font-size: 60rpx;">
			1
		</view>
	</view>
</template>

<script>
	import {
		bannerList,
		cateList,
		infoList
	} from "@/request/api/tiezi.js"
	export default {
		data() {
			return {
				keyword: "",
				list: [],
				list1: [],
				list3: [],
				list2: [],
				allList: [],
				chooseList: [],
				locat: {

				},
				current: 0
			}
		},
		onLoad() {
			cateList().then(res => {
				this.list3 = res.data;
				this.list1 = [...res.data[0].child];
			})
		},
		async onShow() {
			// uni.setStorageSync("locat", {
			// 	"lng": 119.316709,
			// 	"lat": 26.048951
			// })
			cateList().then(res => {
				this.allList = res.data;
				let chooseList = uni.getStorageSync("chooseList");
				if (chooseList) {
					this.chooseList = uni.getStorageSync("chooseList");
				} else {
					this.allList.forEach(item => {
						item.child.forEach(item2 => {
							this.chooseList.push(item2.id)
						})
					})
				}
			})
			let that = this;
			let locat = uni.getStorageSync("locat");
			console.log(locat)
			if (!locat) {
				// uni.getLocation({
				// 	type: 'wgs84',
				// 	success: function(res) {
				// 		uni.hideLoading()
				// 		console.log('当前位置的经度：' + res.longitude);
				// 		console.log('当前位置的纬度：' + res.latitude);
				// 		uni.setStorageSync("locat", {
				// 			lng: res.longitude,
				// 			lat: res.latitude
				// 		})
				// 		that.locat = uni.getStorageSync("locat");
				// 	}
				// });
				await this.getUserLocation()
			} else {
				await this.getUserLocation()
			}
			bannerList().then(res => {
				this.list = res.data
			})
			// infoList({
			// 	pageSize: 100,
			// 	...that.locat
			// }).then(res => {
			// 	console.log(res.data.data)
			// 	that.list2 = res.data.data.map(item => {
			// 		if (item.images) {
			// 			item.images = item.images.split(',');
			// 		}
			// 		return item
			// 	}).filter(it => {
			// 		return it.status == 1
			// 	})
			// })

		},
		methods: {
			async getUserLocation() {
				let that = this;
				try {
					// 检查权限
					const hasPermission = await this.checkLocationPermission();

					if (hasPermission) {
						// 有权限，获取位置
						// uni.getLocation({
						// 	type: 'wgs84', // 国测局坐标系，适用于国内
						// 	geocode: true, // 是否解析地址信息
						// 	success: (res) => {
						// 		console.log('位置信息获取成功：', res);
						// 		// 处理位置信息
						// 	},
						// 	fail: (err) => {
						// 		console.log('位置获取失败：', err);
						// 		uni.showToast({
						// 			title: '位置获取失败，请重试',
						// 			icon: 'none'
						// 		});
						// 	}
						// });
						uni.getLocation({
							type: 'wgs84',
							success: function(res) {
								uni.hideLoading()
								console.log('当前位置的经度：' + res.longitude);
								console.log('当前位置的纬度：' + res.latitude);
								uni.setStorageSync("locat", {
									lng: res.longitude,
									lat: res.latitude
								})
								that.locat = uni.getStorageSync("locat");

								infoList({
									pageSize: 100,
									...that.locat
								}).then(res => {
									console.log(res.data.data)
									that.list2 = res.data.data.map(item => {
										if (item.images) {
											item.images = item.images.split(',');
										}
										return item
									})
								})


							}
						});
					}
				} catch (err) {
					console.log('权限获取失败：', err);
				}
			},
			checkLocationPermission() {
				return new Promise((resolve, reject) => {
					// 首先检查是否有定位权限
					plus.android.requestPermissions(
						["android.permission.ACCESS_FINE_LOCATION",
							"android.permission.ACCESS_COARSE_LOCATION"
						],
						(resultObj) => {
							let result = 0;
							for (let i = 0; i < resultObj.granted.length; i++) {
								let grantedPermission = resultObj.granted[i];
								console.log('已获取的权限：' + grantedPermission);
								result = 1;
							}
							if (resultObj.deniedAlways.length > 0) {
								// 被永久拒绝权限
								console.log('被永久拒绝的权限：' + resultObj.deniedAlways.toString());
								result = 0;
							}
							if (resultObj.deniedPresent.length > 0) {
								// 本次被拒绝权限
								console.log('本次被拒绝的权限：' + resultObj.deniedPresent.toString());
								result = 0;
							}

							if (result === 1) {
								// 已有权限，直接获取位置
								resolve(true);
							} else {
								// 无权限，提示用户去设置
								uni.showModal({
									title: '权限申请',
									content: '请授予定位权限以获取您的位置信息',
									showCancel: false,
									confirmText: '去设置',
									success: (res) => {
										if (res.confirm) {
											// 打开应用设置页面
											if (plus.os.name === "Android") {
												let main = plus.android.runtimeMainActivity();
												let Intent = plus.android.importClass(
													"android.content.Intent");
												let Settings = plus.android.importClass(
													"android.provider.Settings");
												let intent = new Intent(Settings
													.ACTION_APPLICATION_DETAILS_SETTINGS);
												let uri = plus.android.invoke("android.net.Uri",
													"fromParts", "package", main
													.getPackageName(), null);
												plus.android.invoke(intent, "setData", uri);
												main.startActivity(intent);
											} else if (plus.os.name === "iOS") {
												plus.runtime.openURL("app-settings:");
											}
											reject(false);
										}
									}
								});
							}
						},
						(error) => {
							console.log('申请权限错误：' + error.message);
							reject(false);
						}
					);
				});
			},

			navCate() {
				uni.navigateTo({
					url: "/pages/cate/cate"
				})
			},
			click(e) {
				console.log(e)
				this.current = e.index;
				this.list1 = e.child;
			},
			search() {
				if (this.keyword) {
					uni.navigateTo({
						url: "/pages/search/search?keyword=" + this.keyword
					})
				}

			},
			toList(item) {
				uni.navigateTo({
					url: "/pages/list/list?info=" + JSON.stringify(item)
				})
			},
			formatTimestamp(timestamp) {
				// 创建 Date 对象
				const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒

				// 获取年份、月份、日期、小时、分钟、秒
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minute = String(date.getMinutes()).padStart(2, '0');
				const second = String(date.getSeconds()).padStart(2, '0');

				// 返回格式化的日期时间字符串
				return `${year}-${month}-${day}`;
			},
			getUrl(it) {
				let url = "http://ny.fuliaoxx.com" + it;
				// console.log(url)
				return url
			},
			toDetail(item) {
				uni.setStorageSync("goodInfo", item)
				uni.navigateTo({
					url: "/pages/detail/detail?id=" + item.id
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.items {
		.item {
			border-radius: 20rpx;
			background-color: white;
			padding: 30rpx;
			margin-top: 30rpx;

			.top {
				display: flex;
				align-items: center;

				image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 100px;
					margin-right: 20rpx;
				}

				.more {
					width: 40rpx;
					height: 10rpx;
					margin-right: 0;
				}
			}

			.imgs {
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;

				image {
					width: 190rpx;
					height: 190rpx;
					border-radius: 30rpx;
					margin-bottom: 10rpx;
				}
			}
		}
	}

	swiper {
		height: 300rpx;
		border-radius: 20rpx;
		margin-top: 0;
	}

	.swiper-item {
		height: 300rpx;
		border-radius: 20rpx;

		image {
			width: 100%;
			height: 100%;
			border-radius: 20rpx;
		}
	}

	.tabs {
		display: flex;
		border-radius: 20rpx;
		background-color: white;

		.tab {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx;
			max-width: 80rpx;
			font-size: 24rpx;

			image {
				width: 120rpx;
				height: 120rpx;
			}
		}
	}
</style>